//
//  ForumTableViewCell.swift
//  NingguoForum
//
//  Created by zhengsw on 2025/7/17.
//  Copyright © 2025 zhengsw. All rights reserved.
//

import UIKit
import SnapKit
import RxSwift
import YYText

extension String {
    func htmlToAttributedString() -> NSAttributedString? {
        // 使用 YYText 的 HTML 解析功能
        let attributedString = NSMutableAttributedString()
        
        do {
            // 先尝试标准解析
            guard let data = self.data(using: .utf8) else { return nil }
            
            let parsedString = try NSAttributedString(
                data: data,
                options: [
                    .documentType: NSAttributedString.DocumentType.html,
                    .characterEncoding: String.Encoding.utf8.rawValue
                ],
                documentAttributes: nil
            )
            
            attributedString.append(parsedString)
            
            // 设置默认字体和颜色
            attributedString.addAttributes([
                .font: UIFont.systemFont(ofSize: 16),
                .foregroundColor: UIColor.black
            ], range: NSRange(location: 0, length: attributedString.length))
            
            return attributedString
            
        } catch {
            print("HTML 解析错误: \(error)")
            // 如果解析失败，返回纯文本
            return NSAttributedString(string: self)
        }
    }
}
class NGForumTableViewCell: UITableViewCell {
    // MARK: - Properties
        private let disposeBag = DisposeBag()
    
    // MARK: - UI Components
    private lazy var titleLabel: YYLabel = {
        let label = YYLabel()
        label.font = .systemFont(ofSize: 16, weight: .medium)
        label.textColor = .black
        label.numberOfLines = 2
        return label
    }()
    
    private lazy var authorLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 14)
        label.textColor = .darkGray
        return label
    }()
    
    private lazy var readCountLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 12)
        label.textColor = .lightGray
        return label
    }()
    
    private lazy var timeLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 12)
        label.textColor = .lightGray
        return label
    }()
    
    private lazy var thumbnailImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = 4
        return imageView
    }()
    
    // MARK: - Initialization
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        selectionStyle = .none
        
        contentView.addSubview(titleLabel)
        contentView.addSubview(authorLabel)
        contentView.addSubview(readCountLabel)
        contentView.addSubview(timeLabel)
        contentView.addSubview(thumbnailImageView)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(16)
            make.right.equalTo(thumbnailImageView.snp.left).offset(-12)
        }
        
        authorLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.left.equalTo(titleLabel)
        }
        
        readCountLabel.snp.makeConstraints { make in
            make.centerY.equalTo(authorLabel)
            make.left.equalTo(authorLabel.snp.right).offset(12)
        }
        
        timeLabel.snp.makeConstraints { make in
            make.centerY.equalTo(authorLabel)
            make.left.equalTo(readCountLabel.snp.right).offset(12)
        }
        
        thumbnailImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-16)
            make.width.height.equalTo(56)
            make.bottom.lessThanOrEqualToSuperview().offset(-12)
        }
        
        thumbnailImageView.isUserInteractionEnabled = true // 必须打开，否则无法响应点击
        
        let tapGesture = UITapGestureRecognizer()
        thumbnailImageView.addGestureRecognizer(tapGesture)

        tapGesture.rx.event
            .bind { gesture in
                print("图片被点击")
                // 这里可以做更多操作
            }
            .disposed(by: disposeBag)
    }
    
    // MARK: - Configuration
    func configure(with model: ResponseForumDetailListDataModel) {
        
        titleLabel.text = model.title
        authorLabel.text = model.user_name
        readCountLabel.text = model.click
        timeLabel.text = model.lastpost
        //会crash
//        model.title = "<p>这是<strong>粗体</strong>文本</p>"
//        // 转换为富文本
//        if let attributedString = model.title!.htmlToAttributedString() {
//            titleLabel.attributedText = attributedString
//        }
        
        if (model.pics!.count > 0) {
            let picModel = model.pics?.first!
            guard let pic = picModel?.url else { return }
            
            thumbnailImageView.kf.setImage(with: URL(string: pic))
            thumbnailImageView.snp.updateConstraints { make in
                make.width.height.equalTo(56)
            }
        } else {
            thumbnailImageView.snp.updateConstraints { make in
                make.width.height.equalTo(0)
            }
        }
        
    }
}

